package com.hrsaas.ext.git.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.hrsaas.ext.spider.client.HeaderFactory;
import com.hrsaas.ext.spider.core.CookieStore;
import com.hrsaas.ext.spider.core.HttpClient;
import com.hrsaas.ext.spider.handler.TextResponseHandler;
import com.hrsaas.ext.spider.test.handler.HttpClientFactory;
import com.hrsaas.ext.spider.util.JsonUtils;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;

public class GitToken {

	public static void main(String[] args) throws Exception {
		
		HttpClientFactory.getClient().get().
			setURL("http://git.300.cn").
			addHeaders(HeaderFactory.EASY_INDEX).
			execute(new TextResponseHandler() {
				@Override
				protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers, String content) {
					if (status == HttpResponseStatus.OK) {
						return true;
					}
					onErrorResponse(status, headers, content);
					return false;
				}

				@Override
				protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) {
					HttpClientFactory.destory();
				}
				
				@Override
				protected void next(HttpClient client, String object, CookieStore cookieStore, HttpHeaders headers) {
					client.post().setURL("http://git.300.cn/users/sign_in")
						.addHeaders(HeaderFactory.EASY_INDEX)
						.addReferer("http://git.300.cn/users/sign_in")
						.addCookieStore(cookieStore)
						.addQueryPairs(getArgs(object))
						.execute(new TextResponseHandler() {
								@Override
								protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers, String content) {
									if (status == HttpResponseStatus.OK) {
										return true;
									}
									onErrorResponse(status, headers, content);
									return false;
								}
								@Override
								protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) {
									System.out.println(content);
									HttpClientFactory.destory();
								}
								@Override
								protected void next(HttpClient client, String object, CookieStore cookieStore, HttpHeaders headers) {
									client.get().setURL("http://git.300.cn/profile/personal_access_tokens")
										.addHeaders(HeaderFactory.EASY_INDEX)
										.addCookieStore(cookieStore)
										.execute(new TextResponseHandler() {
											@Override
											protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers, String content) {
												if (status == HttpResponseStatus.OK) {
													return true;
												}
												onErrorResponse(status, headers, content);
												return false;
											}
											
											@Override
											protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) {
												System.out.println(content);
												HttpClientFactory.destory();
											}
											
											@Override
											protected void next(HttpClient client, String content, CookieStore cookieStore, HttpHeaders headers) {
												client.post().setURL("http://git.300.cn/profile/personal_access_tokens")
												.addHeaders(HeaderFactory.EASY_INDEX)
												.addReferer("http://git.300.cn/profile/personal_access_tokens")
												.addCookieStore(cookieStore)
												.addQueryPairs(getprivateTokenArgs(content))
												.execute(new TextResponseHandler() {
														@Override
														protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers, String object) {
															if (status == HttpResponseStatus.OK) {
																return true;
															}
															onErrorResponse(status, headers, content);
															return false;
														}
														
														@Override
														protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) {
															System.out.println(content);
															HttpClientFactory.destory();
														}
														@Override
														protected void next(HttpClient client, String content, CookieStore cookieStore, HttpHeaders headers) {
															String key = "id=\"created-personal-access-token\"";
															int beginIndex = content.indexOf(key) + key.length() + 8;
															String private_token = content.substring(beginIndex, beginIndex + 20);
															System.out.println(private_token);
															client.get().setURL("http://git.300.cn/api/v3/projects?private_token=" + private_token)
															.execute(new TextResponseHandler() {
																@Override
																protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers, String object) {
																	if (status == HttpResponseStatus.OK) {
																		return true;
																	}
																	onErrorResponse(status, headers, content);
																	return false;
																}
																@Override
																protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) {
																	System.out.println(content);
																	HttpClientFactory.destory();
																}
																@Override
																protected void next(HttpClient client, String content, CookieStore cookieStore, HttpHeaders headers) {
																	JsonNode result = JsonUtils.toJsonNode(content);
																	if (result != null && !result.isNull() && result.isArray()) {
																		Iterator<JsonNode> elements = result.elements();
																		while (elements.hasNext()) {
																			JsonNode node = elements.next();
																			Long id = node.get("id").asLong();
																			String ssh_url_to_repo = node.get("ssh_url_to_repo").asText();
																			String http_url_to_repo = node.get("http_url_to_repo").asText();
																			String web_url = node.get("web_url").asText();
																			JsonNode namespace = node.get("namespace");
																			String full_path = namespace.get("full_path").asText();
																			System.out.println(http_url_to_repo);
																		}
																	}
																}
															});
														}
												});
											}
										});
								}
						});
				}
			});
		
	}
	
	private static String getCsrfToken(String content) {
		int beginIndex = content.indexOf("csrf-token") + 21;
		String token = content.substring(beginIndex, beginIndex + 88);
		return token;
	}
	
	/**
	 * 登录参数添加
	 * @param object
	 * @return
	 */
	private static Map<String, String> getArgs(String content) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("authenticity_token", getCsrfToken(content));
		paramMap.put("user[login]", "wangxiaoliang");
		paramMap.put("user[password]", "WXL-000000");
		paramMap.put("user[remember_me]", "0");
		return paramMap;
	}
	
	/**
	 * 登录参数添加
	 * @param object
	 * @return
	 */
	private static Map<String, String> getprivateTokenArgs(String content) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("authenticity_token", getCsrfToken(content));
		paramMap.put("personal_access_token[name]", "wangxiaoliang");
		paramMap.put("personal_access_token[expires_at]", "2019-06-02");
		paramMap.put("personal_access_token[scopes][]", "api");
		return paramMap;
	}

}
